<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>ES8- async与await封装AJAX请求</title>
</head>

<body>
  <script>
    // 发送 AJAX 请求,返回的结果是 Promise 对象
    function sendAJAX(url) {
      return new Promise((resolve, reject) => {
        // 1. 创建对象
        const xhr = new XMLHttpRequest();

        // 2. 初始化
        xhr.open('GET', url);

        // 3. 发送
        xhr.send();

        // 4.事件绑定
        xhr.onreadystatechange = function() {
          if(xhr.readyState === 4) {
            if(xhr.status >= 200 && xhr.status < 300) {
              resolve(xhr.response);
            } else {
              reject(xhr.response)
            }
          }
        }
      })
    }

    // Promise then 方法测试
    /* sendAJAX('https://api.apiopen.top/getJoke').then(value => {
      console.log(value)
    }, err => {

    }) */

    async function main() {
      // 发送AJAX  请求
      let result = await sendAJAX('https://api.apiopen.top/getJoke');
      // 再次测试
      let tianqi = await sendAJAX('https://www.tianqiapi.com/api/?version=v1&city=%福州');
      console.log(result, tianqi);
    }

    main();
  </script>
</body>

</html>